//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.prx.prp.R;
import org.prx.prp.MediaPlaybackLayout;
import org.prx.prp.controller.SearchManager;
import org.prx.prp.model.Stream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class SearchViewActivity extends Activity {
	Stream stream;

	ListView listView;
	Intent intent;
	Context mContext;
	@Override
	public void onDestroy() {
		super.onDestroy();
		((MediaPlaybackLayout)findViewById(R.id.media_player)).unRegisterListeners();
	}	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result_view);
		ImageButton searchButton = (ImageButton) findViewById(R.id.search_button);
		mContext = this;
		final EditText searchTextBoxEditText = (EditText) findViewById(R.id.search_query_textbox);
		final ListView liveSearchListView = (ListView) findViewById(R.id.summary_live_search_results_list_view);
		final ListView onDemandSearchResultsView = (ListView) findViewById(R.id.summary_on_demand_search_results_list_view);
		final TextView liveLabel = (TextView) findViewById(R.id.live_search_label);
		final TextView onDemandLabel = (TextView) findViewById(R.id.ondemand_search_label);
		searchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String query = searchTextBoxEditText.getText().toString();				
				String finalq=query.replace(' ','+');				
				if (!searchTextBoxEditText.getText().toString().equals("")) {
					liveSearchListView.setAdapter(new LiveSearchResultListAdapter(mContext,finalq, 0, liveLabel));
					onDemandSearchResultsView.setAdapter(new PodcastSearchResultListAdapter(mContext,finalq, 0, onDemandLabel));
				}
			}
		});

	}
}

class LiveSearchResultListAdapter extends BaseAdapter {
	JSONArray results;
	private LayoutInflater mInflater;
	Context mContext;
	public static int ALL = 1;
	int type;
	String query;

	public LiveSearchResultListAdapter(Context context, String query, int type,
			TextView t) {
		this.mContext = context;
		this.query = query;
		mInflater = LayoutInflater.from(context);
		results = SearchManager.getInstance().getLiveSearch(query);
		if (t != null && results.length() > 0) {
			t.setText("Live Programs:");

			t.setVisibility(TextView.VISIBLE);
		} else if (results.length() == 0) {
			t.setVisibility(TextView.VISIBLE);
			t.setText("No Live programs found");
		}
		this.type = type;
	}

	public int getCount() {
		if (type == ALL)
			return results.length();
		return results.length() > 3 ? 3 : results.length();

	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		View test = null;
		if (results.length() == 0) {
			test = mInflater.inflate(R.layout.list_single_item_view, null);
			TextView infoText = (TextView) test.findViewById(R.id.text1);
			infoText.setText("No results found");
			return test;
		} else if (type != ALL && (results.length() > 3 && position >= 2)) {
			test = mInflater.inflate(R.layout.list_single_item_view, null);
			TextView infoText = (TextView) test.findViewById(R.id.text1);
			infoText.setText("View rest of " + (results.length() - 2) + " results");
			test.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext,
							LiveSearchResultListActivity.class);
					intent.putExtra("query", query);
					mContext.startActivity(intent);
				}
			});
			return test;
		}
		test = mInflater.inflate(R.layout.stream_info_item, null);
		TextView streamNameTextView = (TextView) test.findViewById(R.id.stream_name);
		final String displayName;
		try {
			displayName = results.getJSONObject(position).getJSONObject(
					"stream").getString("display_name");
			streamNameTextView.setText(displayName);
			TextView programTitleTextView = (TextView) test.findViewById(R.id.program_title);
			TextView scheduleTimeTextView = (TextView) test.findViewById(R.id.schedule_time);
			scheduleTimeTextView.setVisibility(TextView.GONE);
			programTitleTextView.setText(results.getJSONObject(position).getJSONObject("stream")
					.getJSONObject("current_program").getString("title"));
			test.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(mContext,
							StationInformationView.class);
					intent.putExtra("STREAM_NAME", displayName);
					try {
						int streamID = results.getJSONObject(position)
								.getJSONObject("stream").getInt("id");
						intent.putExtra("STREAM_ID", streamID);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mContext.startActivity(intent);
				}
			});

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return test;

	}
}

class PodcastSearchResultListAdapter extends BaseAdapter {
	JSONArray results;
	private LayoutInflater mInflater;
	Context mContext;
	public static int ALL = 1;
	int type;
	protected String query;

	public PodcastSearchResultListAdapter(Context context, String query,
			int type, TextView t) {
		this.mContext = context;
		mInflater = LayoutInflater.from(context);
		this.query = query;
		results = SearchManager.getInstance().getPodcastSearch(query);
		this.type = type;
		if (t != null && results.length() > 0) {
			t.setText("On Demand Programs:");

			t.setVisibility(TextView.VISIBLE);
		} else if (results.length() == 0) {
			t.setVisibility(TextView.VISIBLE);
			t.setText("No on demand programs found");
		}
	}

	public int getCount() {
		if (type == ALL)
			return results.length();
		return results.length() > 3 ? 3 : results.length();

	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		View test = null;
		if (results.length() == 0) {
			test = mInflater.inflate(R.layout.list_single_item_view, null);
			TextView infoText = (TextView) test.findViewById(R.id.text1);
			infoText.setText("No results found");
			return test;
		} else if (type != ALL && (results.length() > 3 && position >= 2)) {
			test = mInflater.inflate(R.layout.list_single_item_view, null);
			TextView infoText = (TextView) test.findViewById(R.id.text1);
			infoText.setText("View rest of " + (results.length() - 2) + " results");
			test.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext,
							PodcastSearchResultListActivity.class);
					intent.putExtra("query", query);
					mContext.startActivity(intent);
				}
			});
			return test;
		}
		test = mInflater.inflate(R.layout.stream_info_item, null);
		TextView streamNameTextView = (TextView) test.findViewById(R.id.stream_name);
		final String displayName;
		try {
			displayName = results.getJSONObject(position).getString("program");
			streamNameTextView.setText(displayName);
			TextView programTitleTextView = (TextView) test.findViewById(R.id.program_title);
			programTitleTextView.setText(results.getJSONObject(position).getString("title"));
			TextView scheduleTimeTextView = (TextView) test.findViewById(R.id.schedule_time);
			scheduleTimeTextView.setVisibility(TextView.GONE);

			test.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(mContext, EpisodeDetailsView.class);
					Bundle bundle = new Bundle();
					try {
						bundle.putString("program_name", displayName);
						bundle.putString("url", results.getJSONObject(position)
								.getString("url"));
						bundle.putString("title", results.getJSONObject(position)
								.getString("title"));
						bundle.putString("summary", results.getJSONObject(position)
								.getString("summary"));
						bundle
								.putString("enclosure", results.getJSONObject(
										position).getString("enclosure"));
						intent.putExtras(bundle);
						mContext.startActivity(intent);

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return test;
	}
	
}
